package api

import (
	"encoding/json"
	"log"
	"net/http"
	"strconv"

	"todolist/internal/service"
)

type Handler struct {
    userService *service.UserService
    todoService *service.TodoService
}

func NewHandler(userService *service.UserService, todoService *service.TodoService) *Handler {
    return &Handler{
        userService: userService,
        todoService: todoService,
    }
}

func (h *Handler) Register(w http.ResponseWriter, r *http.Request) {
    var req struct {
        Username string `json:"username"`
        Password string `json:"password"`
    }

    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    user, err := h.userService.Register(req.Username, req.Password)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(user)
}

func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
    var req struct {
        Username string `json:"username"`
        Password string `json:"password"`
    }

    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    token, user, err := h.userService.Login(req.Username, req.Password)
    if err != nil {
        http.Error(w, err.Error(), http.StatusUnauthorized)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(map[string]interface{}{
        "token": token,
        "user":  user,
    })
}

func (h *Handler) GetTasks(w http.ResponseWriter, r *http.Request) {
    userID, _ := r.Context().Value("userID").(int)
    
    // 获取分页参数
    page := r.URL.Query().Get("page")
    pageSize := r.URL.Query().Get("pageSize")
    
    if page == "" {
        page = "1"
    }
    if pageSize == "" {
        pageSize = "10"
    }
    
    pageNum, _ := strconv.Atoi(page)
    size, _ := strconv.Atoi(pageSize)
    
    // 确保页码至少为1
    if pageNum < 1 {
        pageNum = 1
    }
    
    offset := (pageNum - 1) * size
    
    // ... 其余代码保持不变
}

func (h *Handler) CreateTask(w http.ResponseWriter, r *http.Request) {
    // 从上下文获取用户ID
    userID, _ := r.Context().Value("userID").(int)
    log.Printf("Creating task for user ID: %d", userID)
    
    var task struct {
        Title       string `json:"title"`
        Description string `json:"description"`
        Completed   bool   `json:"completed"`
    }

    if err := json.NewDecoder(r.Body).Decode(&task); err != nil {
        log.Printf("Error decoding request: %v", err)
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // 插入任务
    result, err := h.todoService.CreateTask(userID, task.Title, task.Description, task.Completed)
    if err != nil {
        log.Printf("Error creating task: %v", err)
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    log.Printf("Task created successfully: %+v", result)
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(result)
} 